package com.dao;

import com.model.Bill;
import com.utils.DbUntil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class BillDao {

    private Connection connection;

    //在这里初始化  这里获取链接
    public BillDao() {
        connection = DbUntil.getConnection();
    }

    //公有方法 获取所有账单信息
    public List<Bill> getAllBills() {
        List<Bill> bills = new ArrayList<Bill>();
        try {
            Statement statement = connection.createStatement();
            //这里是查询select * from bill
            ResultSet rs = statement.executeQuery("select * from bill");
            while (rs.next()) {
                Bill bill = new Bill();
                bill.setBill_id(rs.getString("bill_id"));
                bill.setUser_id(rs.getString("user_id"));
                bill.setGoods_id(rs.getString("goods_id"));
                bill.setNumber(rs.getString("number"));
                bill.setCreationDate(rs.getLong("creationDate"));
                bills.add(bill);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return bills;
    }

    //通过用户id获取账单
    public List<Bill> getBillsByUserId(int userId)
    {
        List<Bill> bills = new ArrayList<Bill>();
        try {
            Statement statement = connection.createStatement();
            String sql = "select * from bill where user_id='"+userId+"'";
            ResultSet rs = statement.executeQuery(sql);
            while (rs.next()) {
                Bill bill = new Bill();
                bill.setBill_id(rs.getString("bill_id"));
                bill.setUser_id(rs.getString("user_id"));
                bill.setGoods_id(rs.getString("goods_id"));
                bill.setNumber(rs.getString("number"));
                bill.setCreationDate(rs.getLong("creationDate"));
                bills.add(bill);
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }

        return bills;
    }


}
